//
//  XHDataBaseManager.m
//  Bees
//
//  Created by NowYouCanSee on 2018/12/26.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "XHDataBaseManager.h"
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
#import "FMDatabaseAdditions.h"

#define WalletTableVerson 1
#define WalletTableName [NSString stringWithFormat:@"WELLETTABLE%d",WalletTableVerson]

@interface XHDataBaseManager ()

@property(nonatomic, strong) FMDatabase *dbQueue;

@end

@implementation XHDataBaseManager
+ (XHDataBaseManager *)shareInstance {
    static XHDataBaseManager *instance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        instance = [[[self class] alloc] init];
        [instance dbQueue];
    });
    return instance;
}
- (FMDatabase *)dbQueue {
    if (!_dbQueue) {
        NSString *const bees= @"BEES.db";
        NSString *docuPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        NSString *dbPath = [docuPath stringByAppendingPathComponent:bees];
        _dbQueue = [FMDatabase databaseWithPath:dbPath];
        if (_dbQueue && [_dbQueue open]) {
            [self createWalletTable];
        }
    }
    return _dbQueue;
}

- (void)createWalletTable {
    if (![self isTableOK:WalletTableName withDB:self.dbQueue]) {
        NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(ID INTEGER PRIMARY KEY autoincrement, wallet_name TEXT NOT NULL ,wallet_uid TEXT NOT NULL, wallet_public_key TEXT NOT NULL, password_tip TEXT ,wallet_private_AES_key TEXT NOT NULL,password_sha TEXT  NOT NULL,wallet_system TEXT  NOT NULL,balance TEXT,created TEXT,addTime TEXT NOT NULL,contractsJson TEXT,whiteDappJson TEXT,myTokenListJson TEXT,codesJson TEXT,deleteCodesJson TEXT,permission TEXT,reserved TEXT)",WalletTableName];
        BOOL isSuccess = [self.dbQueue executeUpdate:sql];
        NSString *createIndexSQL =[NSString stringWithFormat:@"CREATE unique INDEX IF NOT EXISTS idx_walletId ON %@(wallet_uid);",WalletTableName];
        [self.dbQueue executeUpdate:createIndexSQL];
        if (isSuccess) {
            DLog(@"创建钱包表成功");
        }
    }
  
}
- (BOOL)isTableOK:(NSString *)tableName withDB:(FMDatabase *)db {
    BOOL isOK = NO;
    FMResultSet *rs = [db executeQuery:@"select count(*) as 'count' from sqlite_master where "
                       @"type ='table' and name = ?",
                       tableName];
    while ([rs next]) {
        NSInteger count = [rs intForColumn:@"count"];
        if (0 == count) {
            isOK = NO;
        } else {
            isOK = YES;
        }
    }
    [rs close];
    return isOK;
}

- (void)closeDBForDisconnect {
    self.dbQueue = nil;
}

- (Wallet *)selectCurrentWallet{
    return [self getWallet:CURRENT_WALLET_ID];
}

- (Wallet *)getWallet:(NSString*)wallet_uid{
    if (!wallet_uid.length) {
        return nil;
    }
    __block Wallet *wallet = nil;
        FMResultSet *rs = [self.dbQueue executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@ WHERE wallet_uid = '%@'", WalletTableName, wallet_uid]];
        while ([rs next]) {
            wallet = [[Wallet alloc] init];
            wallet.wallet_uid = [rs stringForColumn:@"wallet_uid"];
            wallet.wallet_name = [rs stringForColumn:@"wallet_name"];
            wallet.wallet_public_key = [rs stringForColumn:@"wallet_public_key"];
            wallet.password_sha = [rs stringForColumn:@"password_sha"];
            wallet.wallet_private_AES_key = [rs stringForColumn:@"wallet_private_AES_key"];
            wallet.wallet_system = [rs stringForColumn:@"wallet_system"];
            wallet.balance = [rs stringForColumn:@"balance"];
            wallet.password_tip = [rs stringForColumn:@"password_tip"];
            wallet.created = [rs stringForColumn:@"created"];
            wallet.addTime = [rs stringForColumn:@"addTime"];
            wallet.contractsJson = [rs stringForColumn:@"contractsJson"];
            wallet.whiteDappJson = [rs stringForColumn:@"whiteDappJson"];
            wallet.myTokenListJson = [rs stringForColumn:@"myTokenListJson"];
            wallet.codesJson = [rs stringForColumn:@"codesJson"];
            wallet.deleteCodesJson = [rs stringForColumn:@"deleteCodesJson"];
            wallet.permission = [rs stringForColumn:@"permission"];
            wallet.reserved = [rs stringForColumn:@"reserved"];
        }
        [rs close];
    return wallet;
}
- (BOOL)removeWallet:(NSString*)wallet_uid{
        if ([wallet_uid length] <= 0)
            return NO;
        NSString *deleteSql =
        [NSString stringWithFormat:@"delete from %@ where %@ = '%@'", WalletTableName, @"wallet_uid", wallet_uid];
     return [self.dbQueue executeUpdate:deleteSql];;
}

- (NSMutableArray<Wallet *> *)selectAllLocalWallet{
    NSMutableArray <Wallet *>*allWallet = [NSMutableArray new];
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM '%@'", WalletTableName];
        FMResultSet *rs = [self.dbQueue executeQuery:sql];
        while ([rs next]) {
            Wallet *wallet = [[Wallet alloc] init];
            wallet.wallet_uid = [rs stringForColumn:@"wallet_uid"];
            wallet.wallet_name = [rs stringForColumn:@"wallet_name"];
            wallet.wallet_public_key = [rs stringForColumn:@"wallet_public_key"];
            wallet.password_sha = [rs stringForColumn:@"password_sha"];
            wallet.wallet_private_AES_key = [rs stringForColumn:@"wallet_private_AES_key"];
            wallet.wallet_system = [rs stringForColumn:@"wallet_system"];
            wallet.password_tip = [rs stringForColumn:@"password_tip"];
            wallet.balance = [rs stringForColumn:@"balance"];
            wallet.created = [rs stringForColumn:@"created"];
            wallet.addTime = [rs stringForColumn:@"addTime"];
            wallet.contractsJson = [rs stringForColumn:@"contractsJson"];
            wallet.whiteDappJson = [rs stringForColumn:@"whiteDappJson"];
            wallet.myTokenListJson = [rs stringForColumn:@"myTokenListJson"];
            wallet.codesJson = [rs stringForColumn:@"codesJson"];
            wallet.deleteCodesJson = [rs stringForColumn:@"deleteCodesJson"];
            wallet.permission = [rs stringForColumn:@"permission"];
            wallet.reserved = [rs stringForColumn:@"reserved"];
            [allWallet addObject:wallet];
        }
        [rs close];
    [allWallet sortUsingComparator:^NSComparisonResult(Wallet* obj1,Wallet* obj2) {
        return [obj1.addTime compare:obj2.addTime];
    }];
    return allWallet;
}

- (BOOL)insertWalletToDB:(Wallet *)wallet {
    if (!wallet.wallet_uid.length) {
        return NO;
    }
    __block BOOL result = NO;
    Wallet *walletCur = [self getWallet:wallet.wallet_uid];
    if (walletCur && [walletCur.wallet_public_key isEqualToString:wallet.wallet_public_key]) {
        [kAppWindow makeToast:XLocalized(@"钱包已经存在!")];
        return NO;
    }
    [USERDEFAULTS setObject:wallet.wallet_uid forKey:kCurrent_wallet_id];
//    if (IsNilOrNull((CURRENT_WALLET_ID))) {
//        [USERDEFAULTS setObject:wallet.wallet_uid forKey:kCurrent_wallet_id];
//    }
    NSString *insertSql = [NSString stringWithFormat:@"REPLACE INTO %@ (wallet_name, wallet_uid, wallet_public_key,password_tip,wallet_private_AES_key,password_sha,wallet_system,balance,created,addTime,contractsJson,whiteDappJson,myTokenListJson,codesJson,deleteCodesJson,permission,reserved) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",WalletTableName];
      result = [self.dbQueue executeUpdate:insertSql, wallet.wallet_name,wallet.wallet_uid, wallet.wallet_public_key, wallet.password_tip, wallet.wallet_private_AES_key,wallet.password_sha,wallet.wallet_system,wallet.balance,wallet.created,wallet.addTime,wallet.contractsJson,wallet.whiteDappJson,wallet.myTokenListJson,wallet.codesJson,wallet.deleteCodesJson,wallet.permission,wallet.reserved];
    return result;
}

- (BOOL)updateWalletToDB:(Wallet *)wallet {
    if (!wallet.wallet_uid.length || ![self getWallet:wallet.wallet_uid]) {
        return NO;
    }
    __block BOOL result = NO;
    NSString *insertSql = [NSString stringWithFormat:@"REPLACE INTO %@ (wallet_name, wallet_uid, wallet_public_key,password_tip,wallet_private_AES_key,password_sha,wallet_system,balance,created,addTime,contractsJson,whiteDappJson,myTokenListJson,codesJson,deleteCodesJson,permission,reserved) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",WalletTableName];
    result = [self.dbQueue executeUpdate:insertSql, wallet.wallet_name,wallet.wallet_uid, wallet.wallet_public_key, wallet.password_tip, wallet.wallet_private_AES_key,wallet.password_sha,wallet.wallet_system,wallet.balance,wallet.created,wallet.addTime,wallet.contractsJson,wallet.whiteDappJson,wallet.myTokenListJson,wallet.codesJson,wallet.deleteCodesJson,wallet.permission,wallet.reserved];
    DLog(@"插入白名单\n%@",wallet.whiteDappJson);
    return result;
}

///给表添加字段
- (void)addField:(NSString*)field{
    if (![self.dbQueue columnExists:field inTableWithName:WalletTableName]){
        NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ TEXT",WalletTableName,field];
        BOOL worked = [self.dbQueue executeUpdate:alertStr];
          if(worked){
              NSLog(@"插入成功");
          }else{
              NSLog(@"插入失败");
          }
    }
}

- (void)saveHistoryWallet:(NSString *)wallet receiveName:(Receive*)receive{
    YYCache *cache = [[YYCache alloc]initWithName:wallet];
    NSDictionary * receives = (NSDictionary *)[cache objectForKey:wallet];
    if (!receives) {
        receives=@{};
    }
    NSMutableDictionary*mReceives = receives.mutableCopy;
    [mReceives setObject:[receive modelToJSONString] forKey:receive.wallet_name];
    [cache setObject:mReceives forKey:wallet];
}
- (NSArray *)getHistoryReceivesWallet:(NSString *)wallet{
    YYCache *cache = [[YYCache alloc]initWithName:wallet];
    NSDictionary * receives = (NSDictionary *)[cache objectForKey:wallet];
    NSMutableArray*all = @[].mutableCopy;
    for (NSString*json in receives.allValues) {
        [all addObject:[Receive modelWithJSON:json]?:[Receive new]];
    }
    [all sortUsingComparator:^NSComparisonResult(Receive* obj1, Receive* obj2) {
        return [obj1.addTime compare:obj2.addTime]==-1;
    }];
    return all.copy;
}
- (void)clearHistoryReceives:(NSString*)wallet{
    YYCache *cache = [[YYCache alloc]initWithName:wallet];
    [cache removeAllObjects];
}

@end
